package com.tarena.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Service;

import com.tarena.dao.EmpDao;
import com.tarena.entity.Emp;
import com.tarena.service.EmpService;

/**
 * liubiao
 */
@Service
public class EmpServiceImpl implements EmpService {
	
	@Resource
	EmpDao  es;

	//service
	public boolean save(Emp emp) {
		Integer sum = es.getSum();
		es.save(emp);
		if (sum < es.getSum()) {
			return true;
		}
		return false;
	}

	//service
	public boolean delete(Integer id) {
		Integer sum = es.getSum();
		es.delete(id);
		if (sum > es.getSum()) {
			return true;
		}
		return false;
	}

	//service
	public void update(Emp emp) {
		es.update(emp);
	}

	//service
	public List<Emp> findById(Integer id) {
		 List<Emp> list=es.findById(id);
		 return list;
	}

	//service
	public List<Emp> findAllEmp() {
		return es.findAllEmp();
	}
	
	//service
	public Integer getSum() {
		return es.getSum();
	}

	//service
	public List<Emp> findByPage(int offset, int limit, Emp emp) throws Exception {
		RowBounds rb = new RowBounds(offset, limit);
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		System.out.println("emp.getName()" + emp.getName());
		System.out.println("emp.getNo()" + emp.getNo());

		SqlSessionFactory sf = (SqlSessionFactory) ctx.getBean(SqlSessionFactory.class);
		SqlSession session = sf.openSession();
		List<Emp> list = new ArrayList<Emp>();
		//如果只有name有值
		if (!"".equals(emp.getName())&&"".equals(emp.getNo())) {
			System.out.println("findEmpByName");
			list = session.selectList("findEmpByName", emp, rb);
			session.close();
		//如果只有no有值
		} else if ("".equals(emp.getName())&&!"".equals(emp.getNo())) {
			System.out.println("findEmpByNo");
			list = session.selectList("findEmpByNo", emp, rb);
			session.close();
		//如果name和no都有值
		}else if(!"".equals(emp.getName())&&!"".equals(emp.getNo())){
			System.out.println("findEmpByParam");
			list = session.selectList("findEmpByParam", emp, rb);
			session.close();
		}
		return list;
	}
	
	//service
	public List<Emp> findByPage(int offset, int limit) throws Exception {
		RowBounds rb = new RowBounds(offset, limit);
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"applicationContext.xml");
		SqlSessionFactory sf = (SqlSessionFactory) ctx.getBean(SqlSessionFactory.class);
		SqlSession session = sf.openSession();
		List<Emp> list = session.selectList("findAllEmp", null, rb);
		session.close();
		return list;
	}

}
